package top.ibase4j.core.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import top.ibase4j.core.Constants;
import top.ibase4j.core.support.http.HttpCode;
import top.ibase4j.core.support.http.SessionUser;
import top.ibase4j.core.util.CacheUtil;
import top.ibase4j.core.util.DataUtil;
import top.ibase4j.core.util.FileUtil;
import top.ibase4j.core.util.PropertiesUtil;
import top.ibase4j.core.util.SecurityUtil;
import top.ibase4j.core.util.WebUtil;

/**
 * 签名验证
 * 
 * @author ShenHuaJie
 * @since 2018年5月12日 下午10:40:38
 */
public class TokenInterceptor extends BaseInterceptor {
	private SignInterceptor signInterceptor;
	// 白名单
	private List<String> whiteUrls;
	private int size = 0;

	public TokenInterceptor() {
		signInterceptor = new SignInterceptor();
		// 读取文件
		String path = TokenInterceptor.class.getResource("/").getFile();
		whiteUrls = FileUtil.readFile(path + "white/tokenWhite.txt");
		size = null == whiteUrls ? 0 : whiteUrls.size();
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String url = request.getRequestURL().toString();
		String refer = request.getHeader("Referer");
		if (refer != null && refer.contains("/swagger") || WebUtil.isWhiteRequest(url, size, whiteUrls)) {
			logger.info("TokenInterceptor skip");
			if (signInterceptor.preHandle(request, response, handler)) {
				return super.preHandle(request, response, handler);
			}
			return false;
		}
		SessionUser session = null;
		// 获取token
		String token = request.getHeader("token");
		logger.debug("Token {}", token);
		if (DataUtil.isNotEmpty(token)) {
			String cacheKey = Constants.TOKEN_KEY + SecurityUtil.encryptMd5(token);
			session = (SessionUser) CacheUtil.getCache().get(cacheKey);
			// 判断token是否过期
			if (DataUtil.isNotEmpty(session)) {
				request.setAttribute(Constants.CURRENT_USER, session);
				CacheUtil.getCache().expire(cacheKey, PropertiesUtil.getInt("APP-TOKEN-EXPIRE", 60 * 60 * 24 * 7));
				logger.info("TokenInterceptor successful");
				if (signInterceptor.preHandle(request, response, handler)) {
					return super.preHandle(request, response, handler);
				}
				return false;
			} else {
				return WebUtil.write(response, HttpCode.UNAUTHORIZED.value(), "会话已过期");
			}
		} else {
			return WebUtil.write(response, HttpCode.UNAUTHORIZED.value(), "请登录");
		}
	}
}
